package org.taurusxi.apiConsumer.mvc.command;

import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixRequestCache;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponents;
import org.springframework.web.util.UriComponentsBuilder;
import org.taurusxi.cloudbean.ApiModel;

/**
 * Created by chengxi on 2017/8/15.
 */
public class ApiModelCommand extends HystrixCommand<ApiModel> {

    private RestTemplate restTemplate;

    private String id;

    public ApiModelCommand(Setter setter,RestTemplate restTemplate){
        super(setter);
        this.restTemplate = restTemplate;
    }

    protected ApiModelCommand(Setter setter) {
        super(setter);
    }

    public ApiModelCommand(RestTemplate restTemplate){
        super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("ApiModelGroup")));
        this.restTemplate = restTemplate;
    }

    @Override
    protected ApiModel run() throws Exception {
        UriComponents components = UriComponentsBuilder.fromHttpUrl("http://USER-SERVICE/index/hello?id="+id).build().encode();
        ApiModel apiModel = restTemplate.getForObject(components.toUri(), ApiModel.class);
        return apiModel;
    }

    @Override
    protected ApiModel getFallback() {
        return ApiModel.ERROR_MODEL;
    }

    @Override
    protected String getCacheKey() {
        return id;
    }

//    public static void flushCache(String id){
//        HystrixRequestCache.getInstance(GETTER_K)
//    }

}
